<template>
  <div style="height: 80vh">
    <el-form
      inline
      :model="state.formdata"
      :rules="formRules"
      ref="queryFormRef"
      label-width="100px"
    >
      <el-form-item label="板卡名称" prop="boardid">
        <el-select
          v-model="state.formdata.boardid"
          style="width: 100px"
          placeholder="请选择器件"
        >
          <el-option
            v-for="item in boarddatas"
            :key="item"
            :label="`板卡 ${item}`"
            :value="item"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="器件名称" prop="componentid">
        <el-select
          v-model="state.formdata.componentid"
          placeholder="请选择器件"
          style="width: 100px"
        >
          <el-option
            v-for="item in numberOptions"
            :key="item"
            :label="`器件 ${item}`"
            :value="item"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="时间段" prop="datetimes">
        <el-date-picker
          v-model="state.formdata.datetimes"
          type="datetimerange"
          value-format="YYYY-MM-DD HH:mm:ss"
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          :clearable="false"
          :disabled-date="disabledDate"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          @click="fetchData"
          :disabled="isLoading"
          :loading="isLoading"
          >查询</el-button
        >
      </el-form-item>
    </el-form>
    <!-- 添加Tabs组件 -->
    <el-tabs v-model="activeTab">
      <el-tab-pane label="趋势图表" name="chart">
        <div ref="chartRef" style="width: 90vw; height: 65vh"></div>
      </el-tab-pane>
      <el-tab-pane label="数据列表" name="data">
        <el-table
          v-if="displayData.length > 0"
          :data="displayData"
          style="width: 90vw; height: 65vh; maign: 20px"
          size="small"
        >
          <el-table-column prop="timestamp" label="时间" width="180" />
          <el-table-column
            prop="temperature"
            label="温度(°C)"
            width="100"
            align="right"
          />
          <el-table-column
            prop="nuclearPowerVoltage"
            label="核电电压(V)"
            align="right"
          />
          <el-table-column
            prop="nuclearPowerCurrent"
            label="核电电流(A)"
            align="right"
          />
          <el-table-column
            prop="auxiliaryPowerVoltage"
            label="辅助电电压(V)"
            align="right"
          />
          <el-table-column
            prop="nuclearPowerLatchCount"
            label="核电闩锁"
            align="right"
          />
          <el-table-column
            prop="auxiliaryPowerCurrent"
            label="辅助电电流(A)"
            align="right"
          />

          <el-table-column
            prop="auxiliaryPowerLatchCount"
            label="辅助电闩锁"
            align="right"
          />
          <el-table-column
            prop="bankVoltage"
            label="RANK电压(V)"
            align="right"
          />
          <el-table-column
            prop="bankCurrent"
            label="RANK电流(A)"
            align="right"
          />

          <el-table-column
            prop="bankLatchCount"
            label="RANK闩锁"
            align="right"
          />
        </el-table>
        <div v-else style="text-align: center; padding: 20px; color: #909399">
          暂无数据
        </div>

        <div
          v-if="displayData.length > 0"
          style="margin-top: 10px; display: flex; justify-content: flex-end"
        >
          <el-pagination
            small
            layout="total, sizes, prev, pager, next, jumper"
            :page-sizes="[20, 50, 100, 200, 500, 1000]"
            :total="testItems.length"
            :page-size="pageSize"
            v-model:current-page="currentPage"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>
<script setup>
import { ref, watch, onMounted, onUnmounted, reactive, computed } from "vue";
import { icBoardTypelist } from "@/api/device/ICBoardType";
import JCdataItem from "./jcdataitem.vue";
import TestLog from "../testcenter/testlog.vue";
import { getOneComponentLine } from "@/api/device/iccomponentBoardStatus";
// 初始化包含 60 个数据的响应式数组
import * as echarts from "echarts";

const chartRef = ref(null);
let chartInstance = null;

// 初始化图表
const initChart = () => {
  if (chartRef.value) {
    chartInstance = echarts.init(chartRef.value);
    const option = {
      title: {
        text: "器件性能指标趋势图",
        left: "center",
      },
      tooltip: {
        trigger: "axis",
        axisPointer: {
          type: "cross",
        },
      },
      legend: {
        data: [
          "温度",
          "核电电压",
          "核电电流",
          "核电闩锁",
          "辅助电电压",
          "辅助电电流",
          "辅助电闩锁",
          "RANK电压",
          "RANK电流",
          "RANK闩锁",
        ],
        top: 30,
      },
      grid: {
        left: "3%",
        right: "7%",
        bottom: "3%",
        containLabel: true,
      },
      xAxis: {
        type: "time", // X轴设置为时间类型
        boundaryGap: false,
        name: "时间",
        axisLabel: {
          formatter: (value) => {
            // 时间格式化处理，显示年月日时分秒
            return echarts.format.formatTime("yyyy-MM-dd hh:mm:ss", value);
          },
        },
      },
      yAxis: [
        {
          type: "value",
          name: "温度 (°C)",

          position: "left",
          axisLine: {
            show: true,
            lineStyle: {
              color: "#ff4d4f",
            },
          },
        },
        {
          type: "value",
          name: "电压 (V)",
          min: 0,

          position: "right",
          offset: 50,
          axisLine: {
            show: true,
            lineStyle: {
              color: "#1890ff",
            },
          },
        },
        {
          type: "value",
          name: "电流 (A)",
          min: 0,
          position: "right",
          axisLine: {
            show: true,
            lineStyle: {
              color: "#7cb305",
            },
          },
        },
        {
          type: "value",
          name: "闩锁计数",
          min: 0,
          position: "right",
          offset: 100,

          axisLine: {
            show: true,
            lineStyle: {
              color: "#eb2f96",
            },
          },
        },
      ],
      series: [
        {
          name: "温度",
          type: "line",
          data: [],
          symbol: "circle",
          symbolSize: 6,
          yAxisIndex: 0,
          lineStyle: {
            width: 2,
          },
          itemStyle: {
            color: "#ff4d4f",
          },
        },
        {
          name: "核电电压",
          type: "line",
          data: [],
          symbol: "circle",
          symbolSize: 6,
          yAxisIndex: 1,
          lineStyle: {
            width: 2,
          },
          itemStyle: {
            color: "#1890ff",
          },
        },
        {
          name: "核电电流",
          type: "line",
          data: [],
          symbol: "circle",
          symbolSize: 6,
          yAxisIndex: 2,
          lineStyle: {
            width: 2,
          },
          itemStyle: {
            color: "#7cb305",
          },
        },
        {
          name: "辅助电电压",
          type: "line",
          data: [],
          symbol: "circle",
          symbolSize: 6,
          yAxisIndex: 1,
          lineStyle: {
            width: 2,
            type: "dashed",
          },
          itemStyle: {
            color: "#fa8c16",
          },
        },
        {
          name: "辅助电电流",
          type: "line",
          data: [],
          symbol: "circle",
          symbolSize: 6,
          yAxisIndex: 2,
          lineStyle: {
            width: 2,
            type: "dashed",
          },
          itemStyle: {
            color: "#722ed1",
          },
        },
        {
          name: "RANK电压",
          type: "line",
          data: [],
          symbol: "circle",
          symbolSize: 6,
          yAxisIndex: 1,
          lineStyle: {
            width: 2,
            type: "dotted",
          },
          itemStyle: {
            color: "#52c41a",
          },
        },
        {
          name: "RANK电流",
          type: "line",
          data: [],
          symbol: "circle",
          symbolSize: 6,
          yAxisIndex: 2,
          lineStyle: {
            width: 2,
            type: "dotted",
          },
          itemStyle: {
            color: "#13c2c2",
          },
        },
        {
          name: "RANK闩锁",
          type: "line",
          data: [],
          symbol: "circle",
          symbolSize: 6,
          yAxisIndex: 3,
          lineStyle: {
            width: 2,
          },
          itemStyle: {
            color: "#eb2f96",
          },
        },
        {
          name: "辅助电闩锁",
          type: "line",
          data: [],
          symbol: "circle",
          symbolSize: 6,
          yAxisIndex: 3,
          lineStyle: {
            width: 2,
            type: "dashed",
          },
          itemStyle: {
            color: "#faad14",
          },
        },
        {
          name: "核电闩锁",
          type: "line",
          data: [],
          symbol: "circle",
          symbolSize: 6,
          yAxisIndex: 3,
          lineStyle: {
            width: 2,
            type: "dotted",
          },
          itemStyle: {
            color: "#f5222d",
          },
        },
      ],
    };
    chartInstance.setOption(option);
  }
};

// 图表配置 - 使用配置驱动的方式减少重复代码
const chartConfig = {
  // 数据映射配置
  dataMap: {
    温度: "temperature",
    核电电压: "nuclearPowerVoltage",
    核电电流: "nuclearPowerCurrent",
    辅助电电压: "auxiliaryPowerVoltage",
    辅助电电流: "auxiliaryPowerCurrent",
    RANK电压: "bankVoltage",
    RANK电流: "bankCurrent",
    RANK闩锁: "bankLatchCount",
    辅助电闩锁: "auxiliaryPowerLatchCount",
    核电闩锁: "nuclearPowerLatchCount",
  },
  // 系列配置
  seriesConfig: [
    { name: "温度", yAxisIndex: 0, color: "#ff4d4f", lineType: "solid" },
    { name: "核电电压", yAxisIndex: 1, color: "#1890ff", lineType: "solid" },
    { name: "核电电流", yAxisIndex: 2, color: "#7cb305", lineType: "solid" },
    { name: "辅助电电压", yAxisIndex: 1, color: "#fa8c16", lineType: "dashed" },
    { name: "辅助电电流", yAxisIndex: 2, color: "#722ed1", lineType: "dashed" },
    { name: "RANK电压", yAxisIndex: 1, color: "#52c41a", lineType: "dotted" },
    { name: "RANK电流", yAxisIndex: 2, color: "#13c2c2", lineType: "dotted" },
    { name: "RANK闩锁", yAxisIndex: 3, color: "#eb2f96", lineType: "solid" },
    { name: "辅助电闩锁", yAxisIndex: 3, color: "#faad14", lineType: "dashed" },
    { name: "核电闩锁", yAxisIndex: 3, color: "#f5222d", lineType: "dotted" },
  ],
};

// 更新图表数据 - 大幅简化数据处理逻辑
const updateChartData = (data) => {
  if (!chartInstance) return;
  // 初始化所有系列数据
  const seriesData = {};
  Object.keys(chartConfig.dataMap).forEach((key) => {
    seriesData[key] = [];
  });

  // 一次性处理所有数据
  data.forEach((item) => {
    const timestamp = item.timestamp; // 使用原始时间戳

    // 遍历所有数据映射，填充对应系列
    Object.entries(chartConfig.dataMap).forEach(([seriesName, dataKey]) => {
      // 只添加有效值
      if (item[dataKey] !== undefined) {
        seriesData[seriesName].push([timestamp, item[dataKey]]);
      }
    });
  });

  // 生成更新选项
  const updateOptions = {
    series: chartConfig.seriesConfig.map((config) => ({
      name: config.name,
      data: seriesData[config.name],
    })),
  };

  chartInstance.setOption(updateOptions);
};
const testItems = ref([]);
const props = defineProps({
  boardid: {
    type: String,
    default: "1",
  },
  testid: {
    type: String,
    default: "",
  },
  enableboardstatus: {
    type: String,
    default: "",
  },
  type: {
    type: String,
    default: "ic",
  },
  deviceid: {
    type: String,
    default: "",
  },
  boardType: {
    type: String,
    default: "",
  },
  datasourceindex: {
    type: String,
    default: "",
  },
  testInfo: {
    type: Object,
    default: () => {},
  },
});
const state = reactive({
  formdata: {
    boardid: props.boardid,
    componentid: 1,
    datetimes: [props.testInfo.starttime, props.testInfo.endtime],
  },
});
const queryFormRef = ref(null);

// 表单校验规则
const formRules = {
  boardid: [
    {
      required: true,
      message: "请选择板卡名称",
      trigger: "change",
    },
  ],
  componentid: [
    {
      required: true,
      message: "请选择器件名称",
      trigger: "change",
    },
  ],
  datetimes: [
    {
      required: true,
      message: "请选择时间段",
      trigger: "change",
    },
    {
      validator: (rule, value, callback) => {
        if (value && value.length === 2) {
          callback();
        } else {
          callback(new Error("请选择完整的时间段"));
        }
      },
      trigger: "change",
    },
  ],
};
const getIndexText = (componentid) => {
  // 计算所在组号和组内序号 //8 一组
  const group = Math.floor((componentid - 1) / 8) + 1;
  const indexInGroup = ((componentid - 1) % 8) + 1;
  return `${props.boardid}-${group}-${indexInGroup}`;
};

const isLoading = ref(false);

// 修改第610行附近的fetchData函数
const fetchData = async () => {
  // 表单验证
  try {
    await queryFormRef.value.validate();

    isLoading.value = true;

    if (state.formdata.boardid && props.testid) {
      getOneComponentLine({
        boardid: state.formdata.boardid,
        testid: props.testid,
        datasourceindex: props.datasourceindex,
        componentid: state.formdata.componentid,
        startTime: state.formdata.datetimes[0],
        endTime: state.formdata.datetimes[1],
      })
        .then((res) => {
          testItems.value = res;
          // 数据加载完成后更新图表
          updateChartData(res);
        })
        .finally(() => {
          isLoading.value = false;
        });
    } else {
      isLoading.value = false;
    }
  } catch (error) {
    isLoading.value = false;
  }
};

const fetchInterval = ref(null);
const boarddatas = ref(
  props.testInfo.enableboardstatus
    .trim()
    .replace(/^"|"$/g, "")
    .replaceAll("IC_", "")
    .split(",")
);
const numberOptions = Array.from({ length: 48 }, (_, i) => i + 1);
// 组件挂载时初始化图表
onMounted(() => {
  initChart();
  window.addEventListener("resize", () => {
    chartInstance?.resize();
  });
  updateDateTimeRange();
});

// 组件卸载时销毁图表
onUnmounted(() => {
  if (chartInstance) {
    chartInstance.dispose();
    chartInstance = null;
  }
  window.removeEventListener("resize", () => {});
});
// 监听数据变化更新图表
watch(
  testItems,
  (newVal) => {
    if (newVal && newVal.length > 0) {
      updateChartData(newVal);
    }
  },
  { deep: true }
);
// 监听props.testInfo变化并更新时间范围
// watch(
//   () => props.testInfo,
//   () => {
//     updateDateTimeRange();
//   },
//   { deep: true }
// );

// 更新时间范围的辅助函数
const updateDateTimeRange = () => {
  console.log("更新时间范围");
  // 首先确保props.testInfo存在
  if (!props.testInfo) {
    // 如果没有测试信息，使用默认时间范围（过去7天到今天）
    const defaultEndDate = new Date();
    const defaultStartDate = new Date();
    defaultStartDate.setDate(defaultEndDate.getDate() - 7); // 过去7天

    state.formdata.datetimes = [
      formatDate(defaultStartDate),
      formatDate(defaultEndDate),
    ];
    return;
  }

  // 检查是否有完整的开始时间和结束时间
  if (props.testInfo.starttime && props.testInfo.endtime) {
    state.formdata.datetimes = [
      props.testInfo.starttime,
      props.testInfo.endtime,
    ];
  } else if (props.testInfo.starttime) {
    // 只有开始时间，结束时间设为今天
    state.formdata.datetimes = [
      props.testInfo.starttime,
      formatDate(new Date()),
    ];
  } else if (props.testInfo.endtime) {
    // 只有结束时间，开始时间设为结束时间的7天前
    const endDate = new Date(props.testInfo.endtime);
    const startDate = new Date(endDate);
    startDate.setDate(endDate.getDate() - 7); // 结束时间的前7天

    state.formdata.datetimes = [formatDate(startDate), props.testInfo.endtime];
  } else {
    // 没有时间信息，使用默认时间范围
    const defaultEndDate = new Date();
    const defaultStartDate = new Date();
    defaultStartDate.setDate(defaultEndDate.getDate() - 7); // 过去7天

    state.formdata.datetimes = [
      formatDate(defaultStartDate),
      formatDate(defaultEndDate),
    ];
  }
};

// 添加日期格式化辅助函数
const formatDate = (date) => {
  if (!(date instanceof Date)) {
    date = new Date(date);
  }

  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  const hours = String(date.getHours()).padStart(2, "0");
  const minutes = String(date.getMinutes()).padStart(2, "0");
  const seconds = String(date.getSeconds()).padStart(2, "0");

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};
// 添加活跃标签页的响应式数据
const activeTab = ref("chart"); // 默认显示图表标签页

// 添加分页相关的响应式数据
const currentPage = ref(1);
const pageSize = ref(20);
const disabledDate = (current) => {
  // 如果没有传入current参数，返回false表示不禁用
  if (!current) return false;

  // 获取当前日期（不包含时间部分）
  const today = new Date();
  today.setHours(0, 0, 0, 0);

  // 检查是否有测试信息
  if (props.testInfo && props.testInfo.starttime && props.testInfo.endtime) {
    // 有完整的测试信息，使用测试信息的时间范围
    const testStartDate = new Date(props.testInfo.starttime);
    const testEndDate = new Date(props.testInfo.endtime);

    // 设置为当天的开始时间
    testStartDate.setHours(0, 0, 0, 0);
    testEndDate.setHours(23, 59, 59, 999);

    // 禁用范围外的日期：早于测试开始时间或晚于测试结束时间或晚于今天
    return current < testStartDate || current > testEndDate || current > today;
  } else if (props.testInfo && props.testInfo.starttime) {
    // 只有开始时间，禁用早于开始时间或晚于今天的日期
    const testStartDate = new Date(props.testInfo.starttime);
    testStartDate.setHours(0, 0, 0, 0);
    return current < testStartDate || current > today;
  } else if (props.testInfo && props.testInfo.endtime) {
    // 只有结束时间，禁用晚于结束时间或晚于今天的日期
    const testEndDate = new Date(props.testInfo.endtime);
    testEndDate.setHours(23, 59, 59, 999);
    return current > testEndDate || current > today;
  } else {
    // 没有测试信息，只禁用未来日期
    return current > today;
  }
};
// 计算当前页显示的数据
const displayData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  // 格式化时间戳显示
  return testItems.value.slice(start, end).map((item) => {
    return {
      ...item,
      timestamp: item.timestamp
        ? new Date(item.timestamp).toLocaleString("zh-CN")
        : "",
    };
  });
});

// 分页处理函数
const handleSizeChange = (size) => {
  pageSize.value = size;
  currentPage.value = 1;
};

const handleCurrentChange = (current) => {
  currentPage.value = current;
};
</script>
